<script setup lang="ts">
import { computed, nextTick, onMounted, ref } from 'vue';

import {
  InputNumber,
  message,
  Modal,
  RadioGroup,
  Textarea,
} from 'ant-design-vue';

import { orderRefundConfirm } from '#/api';

const props = defineProps({
  show: {
    type: Boolean,
    default: false,
  },
  orderNo: {
    type: String,
    default: '',
  },
  refundAmount: {
    type: Number,
    default: 0,
  },
});

const emit = defineEmits(['update:show', 'upOrderData']);
const open = computed({
  get() {
    return props.show;
  },
  set(newValue) {
    emit('update:show', newValue);
  },
});

// 选择的退款比例
const count = ref<number | string>(100);
const options = [
  { label: '100%', value: 100 },
  { label: '70%', value: 70 },
  { label: '50%', value: 50 },
  { label: '30%', value: 30 },
  { label: '自定义金额', value: 'custom' },
];
// 最多可退金额
const maxAmount = computed(() => {
  return Number(props.refundAmount || 0);
});
// 退款金额
const amount = ref('0');
// 原因说明
const reason = ref('');
// 金额输入框的值变化处理
const changeAmount = (value: any) => {
  setTimeout(() => {
    nextTick(() => {
      let validValue = value;
      validValue =
        validValue === '' || validValue === null || validValue === undefined
          ? '0'
          : validValue.replaceAll(/(\.\d{2})\d+$/g, '$1');
      amount.value = validValue;
    });
  }, 10);
};

// 获取最大退款金额 以及百分比计算出的金额数
const getRefundAmount = async (count: number | string) => {
  try {
    if (count !== 'custom') {
      const Proportion = Number(count);
      const calculatedAmount = (maxAmount.value * Proportion) / 100;
      // 四舍五入到两位小数
      const roundedAmount = Math.round(calculatedAmount * 100) / 100;
      amount.value = roundedAmount.toString();
    }
  } catch (error) {
    console.error('获取最大退款金额失败：', error);
  }
};

// 退款比例选择事件
const changeRadio = (e: any) => {
  if (e.target.value === 'custom') {
    amount.value = maxAmount.value.toString();
    return;
  }
  getRefundAmount(e.target.value);
};
const confirmLoading = ref(false);

// 确认事件，处理完成后还需要让父级刷新订单详情页面数据
const handleOk = async () => {
  try {
    if (Number(amount.value) > maxAmount.value) {
      return message.error('退款金额不能大于最大退款金额');
    }
    if (!reason.value) {
      return message.error('请填写退款详细原因');
    }
    confirmLoading.value = true;
    await orderRefundConfirm({
      orderNo: props.orderNo,
      refundReason: reason.value,
      refundMoney: amount.value,
    });
    confirmLoading.value = false;
    open.value = false;
    message.success('操作成功');
    emit('upOrderData');
  } catch (error) {
    confirmLoading.value = false;
    console.error('拒绝取消失败：', error);
  }
};

onMounted(() => {
  getRefundAmount(count.value);
});
</script>

<template>
  <div>
    <Modal v-model:open="open" :confirm-loading="confirmLoading" @ok="handleOk">
      <div class="pb-6">
        <div class="text mt-[-6px] text-lg">取消订单</div>
        <div class="mb-1 mt-3">
          退款比例<span class="ml-1 text-red-600">*</span>
        </div>
        <div class="flex-auto">
          <RadioGroup
            v-model:value="count"
            :options="options"
            button-style="solid"
            option-type="button"
            @change="changeRadio"
          />
        </div>
        <p class="mt-1 text-xs text-gray-400">
          如部分退款，可电话联系客人说明情况后再行退款。
        </p>
        <div class="mb-1 mt-3">
          退款金额<span class="ml-1 text-red-600">*</span>
        </div>
        <!-- :max="maxAmount" -->
        <InputNumber
          v-model:value="amount"
          :disabled="count !== 'custom'"
          :min="0"
          :step="0.01"
          prefix="￥"
          string-mode
          style="width: 100%"
          @change="changeAmount"
        />
        <div class="mb-1 mt-3">
          退款说明<span class="ml-1 text-red-500">*</span>
        </div>
        <Textarea
          v-model:value="reason"
          :auto-size="{ minRows: 5, maxRows: 5 }"
          :maxlength="200"
          :show-count="true"
          placeholder="请输入退款说明"
        />
      </div>
    </Modal>
  </div>
</template>

<style scoped lang="scss">
:deep(.ant-input-number-disabled) {
  background: none;
}

.text {
  color: hsl(var(--card-foreground));
}
</style>
